package cn.com.libertymutual.sp.biz;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.sp.dto.ImageBase64Dto;
import cn.com.libertymutual.sp.service.api.FileUploadService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 头像上传业务逻辑类
 * @author AoYi
 *
 */
@Component
@RefreshScope // 刷新配置无需重启服务
public class FileUploadBiz {

	private Logger log = LoggerFactory.getLogger(getClass());


	@Value("${file.transfer.uploadHeadimgPathUsers}")
	private String uploadHeadimgPathUsers;
	
	@Value("${file.transfer.uploadImagesReportCase}")
	private String uploadImagesReportCase;
	
	// 注入原子性业务逻辑
	@Autowired
	private FileUploadService uploadService;
	@Resource
	private IdentifierMarkBiz identifierMarkBiz;

	/**Remarks: 头像文件上传<br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2017年11月7日下午6:17:35<br>
	 * Project：liberty_sale_plat<br>
	 * @param request
	 * @param response
	 * @param identCode
	 * @param userId
	 * @param file
	 * @return
	 */
	public ServiceResult uploadHeadImg(HttpServletRequest request, HttpServletResponse response, String identCode, String userCode,
			MultipartFile file) {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			// 执行上传
			sr = uploadService.uploadFile(request, userCode, file, this.uploadHeadimgPathUsers,
					this.uploadHeadimgPathUsers.substring(this.uploadHeadimgPathUsers.indexOf("upload/")));
		} catch (Exception e) {
			log.warn("单文件上传异常:" + e.toString());
		}
		return sr;
	}

	public ServiceResult uploadImages(HttpServletRequest request, HttpServletResponse response, String identCode, MultipartFile[] imgFiles) {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			// 执行上传
			sr = uploadService.uploadImages(request, imgFiles, "C:\\app\\saleplatform\\web\\admin-cxb\\image\\");
		} catch (Exception e) {
			log.warn("多文件上传异常:" + e.toString());
		}
		return sr;
	}

	/**Remarks: 头像文件base64编码上传<br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2017年11月7日下午6:17:45<br>
	 * Project：liberty_sale_plat<br>
	 * @param request
	 * @param response
	 * @param identCode
	 * @param userCode
	 * @param imgFileCode
	 * @return
	 */
	public ServiceResult uploadHeadImgByCode(HttpServletRequest request, HttpServletResponse response, String identCode, String userCode,
			String imgFileCode) {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			// 获取
			sr = uploadService.GenerateImage(request, userCode, imgFileCode, this.uploadHeadimgPathUsers,
					this.uploadHeadimgPathUsers.substring(this.uploadHeadimgPathUsers.indexOf("upload/")));
		} catch (Exception e) {
			log.warn("单文件编码上传异常:" + e.toString());
		}
		return sr;
	}

	/**Remarks: 多图文件base64编码上传<br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2017年11月7日下午6:18:04<br>
	 * Project：liberty_sale_plat<br>
	 * @param request
	 * @param response
	 * @param identCode
	 * @param imageBase64Dto
	 * @return
	 */
	public ServiceResult uploadImagesByCode(HttpServletRequest request, HttpServletResponse response, String identCode,
			ImageBase64Dto imageBase64Dto) {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			// 获取
			sr = uploadService.uploadImagesByCode(request, imageBase64Dto, this.uploadImagesReportCase,
					this.uploadImagesReportCase.substring(this.uploadImagesReportCase.indexOf("upload/")));
		} catch (Exception e) {
			log.warn("多图编码上传异常:" + e.toString());
		}
		return sr;
	}

	/**Remarks: 根据文件名输出图片文件流<br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2017年11月7日下午6:18:16<br>
	 * Project：liberty_sale_plat<br>
	 * @param request
	 * @param response
	 * @param identCode
	 * @param fileName
	 * @throws IOException
	 */
	public void outputImgFile(HttpServletRequest request, HttpServletResponse response, String identCode, String fileName) throws IOException {
		OutputStream os = response.getOutputStream();
		try {
			response.reset();
			response.setContentType("image/jpeg; charset=utf-8");
			File file = uploadService.getFile(this.uploadHeadimgPathUsers, fileName, request);
			if (file != null) {
				os.write(FileUtils.readFileToByteArray(file));
				os.flush();
			}
		} catch (Exception e) {
			log.warn("单文件获取流异常:" + e.toString());
		} finally {
			if (os != null) {
				os.close();
			}
		}
	}

	@ApiOperation(value = "获取(输出)图片流__通用", notes = "测试")
	@ApiImplicitParams(value = { @ApiImplicitParam(name = "path", value = "路径"), @ApiImplicitParam(name = "fileName", value = "带后缀的文件全名") })
	@RequestMapping(value = "/getByName", method = RequestMethod.GET)
	public void getByName(String path, String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
		OutputStream os = response.getOutputStream();
		try {
			response.reset();
			response.setContentType("image/jpeg; charset=utf-8");
			File file = uploadService.getFile(path, fileName, request);
			if (file != null) {
				os.write(FileUtils.readFileToByteArray(file));
				os.flush();
			}
		} finally {
			if (os != null) {
				os.close();
			}
		}
	}

	/** Remarks : 单文件下载 <br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2017年9月27日上午11:25:43<br>
	 * Project：liberty_sale_plat<br>
	 */
	@RequestMapping("/downloadFile")
	public void download(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
		OutputStream os = response.getOutputStream();
		try {
			response.reset();
			response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
			response.setContentType("image/jpeg; charset=utf-8");
			os.write(FileUtils.readFileToByteArray(uploadService.getFile(this.uploadHeadimgPathUsers, fileName, request)));
			os.flush();
		} finally {
			if (os != null) {
				os.close();
			}
		}
	}

	/** Remarks : 多文件上传 <br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2017年9月27日上午11:25:51<br>
	 * Project：liberty_sale_plat<br>
	 */
	@RequestMapping("/uploadFiles")
	public void filesUpload(@RequestParam("files") MultipartFile[] files, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		// 判断file数组不能为空并且长度大于0
		if (files != null && files.length > 0) {
			// 循环获取file数组中得文件
			for (int i = 0; i < files.length; i++) {
				MultipartFile file = files[i];
				// 保存文件
				response.setContentType("text/html;charset=utf8");
				response.getWriter().write("<img src='" + uploadService.saveFile(file, this.uploadHeadimgPathUsers, request) + "'/>");
			}
		}
	}

	/** Remarks : 读取上传的所有文件并返回 <br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2017年9月27日上午11:25:58<br>
	 * Project：liberty_sale_plat<br>
	 */
	@RequestMapping("/downloadFiles")
	public ModelAndView list(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String filePath = request.getSession().getServletContext().getRealPath(this.uploadHeadimgPathUsers);
		ModelAndView mav = new ModelAndView("list");
		File uploadDest = new File(filePath);
		String[] fileNames = uploadDest.list();
		for (int i = 0; i < fileNames.length; i++) {
			// 打印出文件名
			String name = request.getContextPath() + "/output.pc?fileName=" + fileNames[i];
			System.out.println(fileNames[i] + "-------------" + name);
			response.setContentType("text/html;charset=utf8");
			response.getWriter().write("<img src='" + name + "'/>");
		}
		return mav;
	}

}
